package io.huaguoguo;

import cn.hutool.core.date.DateUtil;
import io.huaguoguo.conf.ConnectorConf;
import io.huaguoguo.conf.ServerConf;
import io.huaguoguo.connector.Connector;
import io.huaguoguo.connector.NettyEndPoint;
import io.huaguoguo.connector.adapter.HttpAdapter;
import io.huaguoguo.container.Engine;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Hello Jerry!
 * 启动器
 */
@Slf4j
public class BootStrap {
    ServerConf serverConf;
    NettyEndPoint endPoint;
    List<Connector> connectors;
    HttpAdapter httpAdapter = new HttpAdapter();


    public static void main(String[] args) throws Exception {
        long current = DateUtil.current();
        BootStrap bootStrap = new BootStrap();
        bootStrap.start();
        long startCost = DateUtil.current() - current;
        log.info("Hello Jerry! start cost: {}ms",startCost);
    }

    private void start() throws InterruptedException {
        // 加载配置文件
        serverConf = new ServerConf();
        connectors = serverConf.getConnectors();
        // 启动netty http 服务
        endPoint = new NettyEndPoint();
        endPoint.init(connectors);
        // 创建连接器
        createConnector();
        // 创建servlet容器
        Engine engine = new Engine();
        engine.init();
    }

    private void createConnector() throws InterruptedException {

        for (Connector connector : serverConf.getConnectors()) {
            // 打开端口
            endPoint.openConn(connector.getPort());
            connector.start(httpAdapter);
        }

    }


}
